package org.hot100_3;

import javax.print.DocFlavor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class leetcode51 {


    List<List<String>> res = new ArrayList<>();
    public List<List<String>> solveNQueens(int n) {

        char [][] chessboard = new char[n][n];

        for (char [] item:chessboard) {
            Arrays.fill(item,'.');
        }

        backtracking(chessboard,0);

        return res;
    }


    private void backtracking(char [][] chessboard,int row){
        if (row==chessboard.length){
            res.add(arrToList(chessboard));
            return;
        }

        for (int i = 0; i < chessboard.length; i++) {
            if (isValid(row,i,chessboard)){
                chessboard[row][i]='Q';

                backtracking(chessboard,row+1);

                chessboard[row][i]='.';
            }
        }
    }

    private boolean isValid(int row ,int col, char[][] chessboard){

        int n = chessboard.length;

        //判断同一列
        for (int i = row-1; i >=0 ; i--) {
            if (chessboard[i][col]=='Q'){
                return false;
            }
        }

        //判断45度
        for (int i = row-1,j=col-1; i >=0 && j>=0 ; i--,j--) {
            if (chessboard[i][j]=='Q'){
                return false;
            }
        }

        //判断135度
        for (int i = row-1,j=col+1; i >=0 && j<n ; i--,j++) {
            if (chessboard[i][j]=='Q'){
                return false;
            }
        }

        return true;
    }

    private List<String> arrToList(char [][]chessboard){
        List<String> list = new ArrayList<>();

        for (char[] item : chessboard) {
            list.add(new String(item));
        }

        return list;
    }
}
